using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Interop;
using Microsoft.Win32;

namespace LarkShot
{
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private AppConfig _config;
        private GlobalHotKeyManager _hotKeyManager;
        private NotifyIcon _notifyIcon;
        private IntPtr _windowHandle;
        private bool _isClosing = false;

        public event PropertyChangedEventHandler PropertyChanged;

        public string HotKey
        {
            get => _config.HotKey;
            set
            {
                _config.HotKey = value;
                OnPropertyChanged(nameof(HotKey));
                UpdateHotKey();
            }
        }

        public bool AutoCrop
        {
            get => _config.AutoCrop;
            set
            {
                _config.AutoCrop = value;
                OnPropertyChanged(nameof(AutoCrop));
            }
        }

        public bool ShowToastNotification
        {
            get => _config.ShowToastNotification;
            set
            {
                _config.ShowToastNotification = value;
                OnPropertyChanged(nameof(ShowToastNotification));
            }
        }

        public string ScreenshotPath
        {
            get => _config.ScreenshotPath;
            set
            {
                _config.ScreenshotPath = value;
                OnPropertyChanged(nameof(ScreenshotPath));
            }
        }

        public string TargetWindowTitle => _config.TargetWindowTitle;

        public MainWindow()
        {
            InitializeComponent();
            _config = AppConfig.Load();
            _hotKeyManager = new GlobalHotKeyManager();
            
            DataContext = this;
            InitializeNotifyIcon();
            
            // 确保截图目录存在
            _config.EnsureScreenshotDirectory();
            
            Loaded += MainWindow_Loaded;
            Closing += MainWindow_Closing;
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            _windowHandle = new WindowInteropHelper(this).Handle;
            _hotKeyManager.HotKeyPressed += OnHotKeyPressed;
            
            // 设置界面控件的初始值
            HotKeyComboBox.Text = _config.HotKey;
            AutoCropCheckBox.IsChecked = _config.AutoCrop;
            ToastNotificationCheckBox.IsChecked = _config.ShowToastNotification;
            ScreenshotPathTextBox.Text = _config.ScreenshotPath;
            
            // 立即注册热键并更新状态
            UpdateHotKey();
            UpdateInitialStatus();
        }

        private void InitializeNotifyIcon()
        {
            _notifyIcon = new NotifyIcon
            {
                Icon = LoadApplicationIcon(),
                Text = "LarkShot - 智能截图工具",
                Visible = false
            };

            var contextMenu = new ContextMenuStrip();
            contextMenu.Items.Add("显示主界面", null, (s, e) => ShowMainWindow());
            contextMenu.Items.Add("打开截图文件夹", null, (s, e) => OpenScreenshotFolder());
            contextMenu.Items.Add("-");
            contextMenu.Items.Add("退出", null, (s, e) => ExitApplication());

            _notifyIcon.ContextMenuStrip = contextMenu;
            _notifyIcon.DoubleClick += (s, e) => ShowMainWindow();
        }

        private System.Drawing.Icon LoadApplicationIcon()
        {
            try
            {
                // 首先尝试从应用程序目录加载 ico 文件
                string iconPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "larkshot.ico");
                if (File.Exists(iconPath))
                {
                    return new System.Drawing.Icon(iconPath);
                }

                // 尝试从嵌入资源加载图标
                string exePath = Process.GetCurrentProcess().MainModule.FileName;
                var extractedIcon = System.Drawing.Icon.ExtractAssociatedIcon(exePath);
                if (extractedIcon != null)
                {
                    return extractedIcon;
                }
            }
            catch (Exception ex)
            {
                // 图标加载失败时记录但不显示错误给用户
                Debug.WriteLine($"图标加载失败: {ex.Message}");
            }
            
            // 最后回退到系统默认图标
            return SystemIcons.Application;
        }

        private void ShowNotification(string title, string message, ToolTipIcon icon)
        {
            try
            {
                if (_notifyIcon != null)
                {
                    // 确保托盘图标设置正确
                    if (_notifyIcon.Icon == null)
                    {
                        _notifyIcon.Icon = LoadApplicationIcon();
                    }

                    // 确保托盘图标可见
                    bool wasVisible = _notifyIcon.Visible;
                    if (!wasVisible)
                    {
                        _notifyIcon.Visible = true;
                    }

                    // 显示通知，使用应用程序图标
                    _notifyIcon.ShowBalloonTip(3000, title, message, icon);

                    // 如果之前不可见则在短暂延迟后隐藏
                    if (!wasVisible)
                    {
                        var timer = new System.Windows.Threading.DispatcherTimer
                        {
                            Interval = TimeSpan.FromSeconds(4)
                        };
                        timer.Tick += (s, e) =>
                        {
                            timer.Stop();
                            if (_notifyIcon != null && !IsVisible)
                            {
                                _notifyIcon.Visible = false;
                            }
                        };
                        timer.Start();
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"显示通知失败: {ex.Message}");
            }
        }

        private void UpdateHotKey()
        {
            try
            {
                _hotKeyManager.UnregisterHotKey();
                if (_windowHandle != IntPtr.Zero)
                {
                    var key = GlobalHotKeyManager.ParseHotKey(_config.HotKey);
                    _hotKeyManager.RegisterHotKey(_windowHandle, key);
                }
                UpdateStatus();
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"热键注册失败: {ex.Message}", "错误");
            }
        }

        private void OnHotKeyPressed()
        {
            try
            {
                var targetWindow = ScreenshotCapture.FindTargetWindow(_config.TargetWindowTitle);
                if (targetWindow == IntPtr.Zero)
                {
                    UpdateStatus($"未找到目标窗口: {_config.TargetWindowTitle}");
                    return;
                }

                var bitmap = ScreenshotCapture.CaptureWindow(targetWindow);
                if (bitmap == null)
                {
                    UpdateStatus("截图失败");
                    return;
                }

                if (_config.AutoCrop)
                {
                    bitmap = ScreenshotCapture.AutoCropBlackBorders(bitmap);
                }

                string fileName = $"screenshot_{DateTime.Now:yyyyMMdd_HHmmss}.png";
                string filePath = Path.Combine(_config.ScreenshotPath, fileName);
                
                ScreenshotCapture.SaveScreenshot(bitmap, filePath);
                bitmap.Dispose();

                UpdateStatus($"截图已保存: {fileName}");
                
                // 根据配置决定是否显示通知
                if (_config.ShowToastNotification)
                {
                    ShowNotification("截图成功", $"截图已保存到: {fileName}", ToolTipIcon.Info);
                }
            }
            catch (Exception ex)
            {
                UpdateStatus($"截图失败: {ex.Message}");
            }
        }

        private void UpdateStatus(string message = null)
        {
            if (message != null)
            {
                StatusTextBlock.Text = $"{DateTime.Now:HH:mm:ss} - {message}";
            }
            else
            {
                var targetWindow = ScreenshotCapture.FindTargetWindow(_config.TargetWindowTitle);
                string windowStatus = targetWindow != IntPtr.Zero ? "已找到" : "未找到";
                StatusTextBlock.Text = $"目标程序: {_config.TargetWindowTitle} ({windowStatus})\n" +
                                     $"快捷键: {_config.HotKey}\n" +
                                     $"自动裁剪: {(_config.AutoCrop ? "启用" : "禁用")}\n" +
                                     $"Toast通知: {(_config.ShowToastNotification ? "启用" : "禁用")}\n" +
                                     $"保存路径: {_config.ScreenshotPath}";
            }
        }

        private void UpdateInitialStatus()
        {
            try
            {
                // 检查目标程序是否运行
                var targetWindow = ScreenshotCapture.FindTargetWindow(_config.TargetWindowTitle);
                bool programFound = targetWindow != IntPtr.Zero;
                
                // 检查配置文件是否正确加载
                bool configLoaded = !string.IsNullOrEmpty(_config.HotKey) && 
                                   !string.IsNullOrEmpty(_config.ScreenshotPath);
                
                if (programFound && configLoaded)
                {
                    StatusTextBlock.Text = "就绪";
                }
                else
                {
                    string issues = "";
                    if (!programFound)
                    {
                        issues += $"未找到目标程序: {_config.TargetWindowTitle}";
                    }
                    if (!configLoaded)
                    {
                        if (!string.IsNullOrEmpty(issues)) issues += "\n";
                        issues += "配置文件读取失败";
                    }
                    StatusTextBlock.Text = issues;
                }
            }
            catch (Exception ex)
            {
                StatusTextBlock.Text = $"状态检查失败: {ex.Message}";
            }
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                _config.HotKey = HotKeyComboBox.Text;
                _config.AutoCrop = AutoCropCheckBox.IsChecked ?? false;
                _config.ShowToastNotification = ToastNotificationCheckBox.IsChecked ?? true;
                _config.ScreenshotPath = ScreenshotPathTextBox.Text;
                // 不再保存目标窗口标题，因为它是硬编码的
                
                _config.EnsureScreenshotDirectory();
                _config.Save();
                
                UpdateHotKey();
                UpdateStatus("配置已保存");
                
                System.Windows.MessageBox.Show("配置保存成功！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"保存配置失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void BrowseFolderButton_Click(object sender, RoutedEventArgs e)
        {
            using var dialog = new FolderBrowserDialog();
            dialog.SelectedPath = _config.ScreenshotPath;
            dialog.Description = "选择截图保存路径";
            
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ScreenshotPathTextBox.Text = dialog.SelectedPath;
            }
        }

        private void OpenFolderButton_Click(object sender, RoutedEventArgs e)
        {
            OpenScreenshotFolder();
        }

        private void OpenScreenshotFolder()
        {
            try
            {
                if (Directory.Exists(_config.ScreenshotPath))
                {
                    Process.Start("explorer.exe", _config.ScreenshotPath);
                }
                else
                {
                    System.Windows.MessageBox.Show("截图文件夹不存在", "提示");
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"打开文件夹失败: {ex.Message}", "错误");
            }
        }

        private void HideToTrayButton_Click(object sender, RoutedEventArgs e)
        {
            HideToSystemTray();
        }

        private void HideToSystemTray()
        {
            Hide();
            _notifyIcon.Visible = true;
            ShowNotification("LarkShot", "程序已最小化到系统托盘", ToolTipIcon.Info);
        }

        private void ShowMainWindow()
        {
            Show();
            WindowState = WindowState.Normal;
            Activate();
            _notifyIcon.Visible = false;
        }

        private void ExitApplication()
        {
            _isClosing = true;
            try
            {
                _hotKeyManager?.UnregisterHotKey();
                if (_notifyIcon != null)
                {
                    _notifyIcon.Visible = false;
                    _notifyIcon.Dispose();
                }
                
                System.Windows.Application.Current.Shutdown();
                Environment.Exit(0);
            }
            catch
            {
                Environment.Exit(0);
            }
        }

        private void MainWindow_Closing(object sender, CancelEventArgs e)
        {
            if (!_isClosing)
            {
                e.Cancel = true;
                HideToSystemTray();
                return;
            }

            // 完全清理资源
            try
            {
                _hotKeyManager?.Dispose();
                if (_notifyIcon != null)
                {
                    _notifyIcon.Visible = false;
                    _notifyIcon.Dispose();
                }
                
                // 强制退出应用程序
                System.Windows.Application.Current.Shutdown();
                Environment.Exit(0);
            }
            catch
            {
                // 如果正常退出失败，强制终止进程
                Environment.Exit(0);
            }
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
